﻿Imports System.Data
Imports System.Collections.ObjectModel
Imports System.Text

Class CMConfigCOVAFTLPorvenir
    Private claveEnEdicion As CClavesOp
    Private BrokerEnEdicion As CBrokerPorvenir
    Private brokerCambio As CBrokerPorvenir
    Private obcBrokersPorvenir As New ObservableCollection(Of CBrokerPorvenir)
    Private lstClavesOp As New ObservableCollection(Of CClavesOp)
    Dim COVAFTLServicio As New CCOVAFTLServicio()
    Dim strFaxAuxCambio As String = String.Empty

#Region "Carga página"
    Private Sub CMConfigCOVAFTLPorvenir_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs) Handles Me.Loaded
        Try
            CargaBrokers()
            CargaClavesOP()
            Mouse.OverrideCursor = Cursors.Arrow
        Catch ex As Exception
            Dim intErrorCargaInicial As Integer = CUtileria.GrabarBitacora("ConfigBrokerPorvenir", "Carga página", ex.Message)
            CUtileria.CompletarRegBitacora(intErrorCargaInicial)

            Mouse.OverrideCursor = Cursors.Arrow

            MessageBox.Show("Error TI500. " & ex.Message, "Carga página configuración COVAFTL Porvenir", MessageBoxButton.OK, MessageBoxImage.Error)
        End Try
    End Sub
#End Region

#Region "Carga inicial"
    Private Sub CargaBrokers()
        Dim dt As New DataTable()
        Dim intBitacoraDecalog As Integer

        intBitacoraDecalog = CUtileria.GrabarBitacora("ConfigBrokerPorvenir", "Carga inicial de brokers", "Carga de los brokers registrados en la base de datos")

        dt = COVAFTLServicio.ObtieneBrokersPorvenir()

        For Each drAux As DataRow In dt.Rows
            obcBrokersPorvenir.Add(New CBrokerPorvenir(drAux("FAX_NUM"), drAux("BROKER_COD")))
        Next

        grdBrokersPorvenir.ItemsSource = obcBrokersPorvenir
        grdBrokersPorvenir.UpdateLayout()

        CUtileria.CompletarRegBitacora(intBitacoraDecalog)
    End Sub
#End Region

#Region "Aregar broker"
    Private Sub btnAgregarBroker_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAgregarBroker.Click
        Dim cbpNuevo As New CBrokerPorvenir("Escribe FAX_NUM...", "Escribe BROKER_COD ...", True)

        grdBrokersPorvenir.CancelEdit(DataGridEditingUnit.Cell)
        grdBrokersPorvenir.UnselectAllCells()
        grdBrokersPorvenir.UpdateLayout()

        obcBrokersPorvenir.Add(cbpNuevo)

        grdBrokersPorvenir.ScrollIntoView(cbpNuevo)
        grdBrokersPorvenir.UpdateLayout()

        Dim celda As DataGridCell = ObtenerCelda(grdBrokersPorvenir, grdBrokersPorvenir.Items.Count - 1, 0)
        If Not celda Is Nothing Then
            celda.Focus()
            grdBrokersPorvenir.BeginEdit()
            celda.IsSelected = True
        End If
    End Sub
#End Region

#Region "Eliminar broker"
    Private Sub btnEliminarBroker_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnEliminarBroker.Click
        If grdBrokersPorvenir.SelectedCells.Count > 0 Then
            Dim msgResultado As MessageBoxResult = MessageBox.Show("¿Está seguro de borrar todos los registros seleccionados?", "Borrar registros", MessageBoxButton.YesNo, MessageBoxImage.Question)

            If msgResultado = MessageBoxResult.Yes Then
                Try
                    Dim brokersEliminar As New ObservableCollection(Of CBrokerPorvenir)
                    Dim strBrokersNoBorrados As String = String.Empty

                    Mouse.OverrideCursor = Cursors.Wait

                    For Each celda As DataGridCellInfo In grdBrokersPorvenir.SelectedCells
                        brokersEliminar.Add(CType(celda.Item, CBrokerPorvenir))
                    Next

                    For Each T As CBrokerPorvenir In brokersEliminar
                        Try
                            Dim blnBorrado As Boolean = COVAFTLServicio.EliminaBrokerPorvenir(T.FAX_NUM, T.BROKER_COD)

                            If Not blnBorrado Then
                                strBrokersNoBorrados = strBrokersNoBorrados & T.FAX_NUM & ","
                            Else
                                obcBrokersPorvenir.Remove(T)
                            End If
                        Catch ex As Exception
                            strBrokersNoBorrados = strBrokersNoBorrados & T.FAX_NUM & ","
                        End Try
                    Next

                    grdBrokersPorvenir.UpdateLayout()

                    If strBrokersNoBorrados.Length > 0 Then
                        strBrokersNoBorrados = strBrokersNoBorrados.Substring(0, strBrokersNoBorrados.Length - 1)

                        Mouse.OverrideCursor = Cursors.Arrow

                        MessageBox.Show("No se borraron los brokers con el FAX_NUM = " & strBrokersNoBorrados, "Borrar registros", MessageBoxButton.OK, MessageBoxImage.Error)
                    End If

                    Mouse.OverrideCursor = Cursors.Arrow
                Catch ex As Exception
                    Dim intErrorBorrado As Integer = CUtileria.GrabarBitacora("ConfigBrokerPorvenir", "Borrar registros", ex.Message)

                    Mouse.OverrideCursor = Cursors.Arrow

                    MessageBox.Show("Error TI500. " & ex.Message, "Borrar registros", MessageBoxButton.OK, MessageBoxImage.Error)
                End Try
            End If
        Else
            MessageBox.Show("Favor de seleccionar los registros que desea borrar", "Borrar registros", MessageBoxButton.OK, MessageBoxImage.Warning)
        End If
    End Sub
#End Region

#Region "Generales"
    Private Function ObtenerCelda(ByRef miDataGrid As DataGrid, ByVal indexRow As Integer, ByVal indexCol As Integer) As DataGridCell
        Try
            Dim row As DataGridRow = miDataGrid.ItemContainerGenerator.ContainerFromIndex(indexRow)
            Dim cellContent As Object = miDataGrid.Columns(indexCol).GetCellContent(row)

            Dim objDepend As DependencyObject = cellContent
            Dim celda As DataGridCell = Nothing

            While Not objDepend Is Nothing

                If objDepend.GetType().Name = "DataGridCell" Then
                    celda = objDepend
                    Return celda
                End If
                objDepend = VisualTreeHelper.GetParent(objDepend)
            End While
        Catch ex As Exception
            Throw ex
        End Try

        Return Nothing
    End Function

    Private Sub grdBrokersPorvenir_BeginningEdit(ByVal sender As System.Object, ByVal e As System.Windows.Controls.DataGridBeginningEditEventArgs) Handles grdBrokersPorvenir.BeginningEdit
        BrokerEnEdicion = grdBrokersPorvenir.CurrentItem
        strFaxAuxCambio = BrokerEnEdicion.FAX_NUM
    End Sub

    Private Sub grdBrokersPorvenir_CellEditEnding(ByVal sender As System.Object, ByVal e As System.Windows.Controls.DataGridCellEditEndingEventArgs) Handles grdBrokersPorvenir.CellEditEnding
        Dim brokerActual As New CBrokerPorvenir()

        Select Case e.EditAction
            Case DataGridEditAction.Commit
                If Not sender.CurrentItem Is Nothing Then
                    Dim Columna As Integer = e.Column.DisplayIndex
                    Dim strFaxAnterior As String, strBrokerAnterior As String

                    brokerActual = TryCast(grdBrokersPorvenir.CurrentCell.Item, CBrokerPorvenir)

                    If brokerActual.Equals(BrokerEnEdicion) = False Then
                        CType(sender, DataGrid).CancelEdit(DataGridEditingUnit.Cell)
                        Exit Sub
                    End If

                    strFaxAnterior = brokerActual.FAX_NUM
                    strBrokerAnterior = brokerActual.BROKER_COD

                    If Columna = 0 Then
                        Dim txtContenidoCelda As Object = grdBrokersPorvenir.Columns(Columna).GetCellContent(grdBrokersPorvenir.CurrentItem)
                        Dim txtContenidoCeldaAux As Object = grdBrokersPorvenir.Columns(1).GetCellContent(grdBrokersPorvenir.CurrentItem)

                        If txtContenidoCelda.Text.ToString.Length = 0 Then
                            MessageBox.Show("El campo FAX_NUM no puede ser vacío", "Alta/Actualización registro", MessageBoxButton.OK, MessageBoxImage.Error)

                            CType(sender, DataGrid).CancelEdit(DataGridEditingUnit.Cell)
                            Exit Sub
                        ElseIf txtContenidoCelda.Text.ToString.ToUpper.Equals(strFaxAuxCambio.ToUpper) Then
                            CType(sender, DataGrid).CancelEdit(DataGridEditingUnit.Cell)
                            Exit Sub
                        End If

                        BrokerEnEdicion.FAX_NUM = txtContenidoCelda.Text
                        BrokerEnEdicion.BROKER_COD = txtContenidoCeldaAux.Text
                    ElseIf Columna = 1 Then
                        Dim txtContenidoCelda As Object = grdBrokersPorvenir.Columns(Columna).GetCellContent(grdBrokersPorvenir.CurrentItem)
                        Dim txtContenidoCeldaAux As Object = grdBrokersPorvenir.Columns(0).GetCellContent(grdBrokersPorvenir.CurrentItem)

                        BrokerEnEdicion.FAX_NUM = txtContenidoCeldaAux.Text
                        BrokerEnEdicion.BROKER_COD = txtContenidoCelda.Text
                    End If

                    BrokerEnEdicion.EsEditableNuevo = brokerActual.EsEditableNuevo

                    If BrokerEnEdicion.EsEditableNuevo Then
                        Try
                            Mouse.OverrideCursor = Cursors.Wait
                            Dim intGuardaBroker As Integer = CUtileria.GrabarBitacora("ConfigBrokerPorvenir", "Alta broker", "Se registra el broker porvenir: FAX_NUM = " & BrokerEnEdicion.FAX_NUM & ", BROKER_COD = " & BrokerEnEdicion.BROKER_COD)

                            Dim intResultado As Integer = COVAFTLServicio.AltaBrokerPorvenir(BrokerEnEdicion.FAX_NUM, BrokerEnEdicion.BROKER_COD, CServiciosMacrosSyBaseDB.IDUSUARIO)

                            CUtileria.CompletarRegBitacora(intGuardaBroker)

                            If intResultado = 1 Then
                                Mouse.OverrideCursor = Cursors.Arrow

                                MessageBox.Show("Ya existe un broker con el FAX_NUM ingresado", "Alta broker", MessageBoxButton.OK, MessageBoxImage.Error)

                                CType(sender, DataGrid).CancelEdit(DataGridEditingUnit.Cell)
                            ElseIf intResultado = -1 Then
                                Mouse.OverrideCursor = Cursors.Arrow

                                MessageBox.Show("Error al intentar guardar el broker", "Alta broker", MessageBoxButton.OK, MessageBoxImage.Error)

                                CType(sender, DataGrid).CancelEdit(DataGridEditingUnit.Cell)
                            ElseIf intResultado = 0 Then
                                brokerActual.EsEditableNuevo = False
                                BrokerEnEdicion.EsEditableNuevo = False
                            End If

                            Mouse.OverrideCursor = Cursors.Arrow
                        Catch ex As Exception
                            Mouse.OverrideCursor = Cursors.Arrow

                            MessageBox.Show("Error TI500. Error al intentar guardar el broker: " & ex.Message, "Alta de broker", MessageBoxButton.OK, MessageBoxImage.Error)

                            CType(sender, DataGrid).CancelEdit(DataGridEditingUnit.Cell)
                        End Try
                    Else
                        Try
                            Mouse.OverrideCursor = Cursors.Wait

                            Dim brokerActualizado As New CBrokerPorvenir()
                            brokerActualizado.FAX_NUM = strFaxAnterior
                            brokerActualizado.BROKER_COD = strBrokerAnterior

                            Dim intActualizaBroker As Integer = CUtileria.GrabarBitacora("ConfigBrokerPorvenir", "Actualiza broker", "Se actualiza el broker porvenir.Inicio: FAX_NUM = " & strFaxAnterior & ", BROKER_COD = " & strBrokerAnterior & ".Fin: FAX_NUM = " & BrokerEnEdicion.FAX_NUM & ", BROKER_COD = " & BrokerEnEdicion.BROKER_COD)

                            Dim intResultadoAct As Integer = COVAFTLServicio.ActualizaBrokerPorvenir(brokerActualizado, BrokerEnEdicion, CServiciosMacrosSyBaseDB.IDUSUARIO, Columna)

                            CUtileria.CompletarRegBitacora(intActualizaBroker)

                            If intResultadoAct = 1 Then
                                Mouse.OverrideCursor = Cursors.Arrow

                                MessageBox.Show("Ya existe un broker con el FAX_NUM ingresado", "Actualiza broker", MessageBoxButton.OK, MessageBoxImage.Error)

                                BrokerEnEdicion.FAX_NUM = strFaxAnterior
                                BrokerEnEdicion.BROKER_COD = strBrokerAnterior

                                CType(sender, DataGrid).CancelEdit(DataGridEditingUnit.Cell)

                            ElseIf intResultadoAct = -1 Then
                                Mouse.OverrideCursor = Cursors.Arrow

                                MessageBox.Show("Error al intentar actualizar el broker", "Actualiza broker", MessageBoxButton.OK, MessageBoxImage.Error)

                                BrokerEnEdicion.FAX_NUM = strFaxAnterior
                                BrokerEnEdicion.BROKER_COD = strBrokerAnterior

                                CType(sender, DataGrid).CancelEdit(DataGridEditingUnit.Cell)
                            End If

                            Mouse.OverrideCursor = Cursors.Arrow
                        Catch ex As Exception
                            BrokerEnEdicion.FAX_NUM = strFaxAnterior
                            BrokerEnEdicion.BROKER_COD = strBrokerAnterior

                            Mouse.OverrideCursor = Cursors.Arrow

                            MessageBox.Show("Error TI500. Error al intentar actualizar el broker: " & ex.Message, "Actualización de broker", MessageBoxButton.OK, MessageBoxImage.Error)

                            CType(sender, DataGrid).CancelEdit(DataGridEditingUnit.Cell)
                        End Try

                    End If

                    grdBrokersPorvenir.UpdateLayout()
                Else
                    CType(sender, DataGrid).CancelEdit(DataGridEditingUnit.Cell)
                End If

            Case DataGridEditAction.Cancel

                brokerCambio = TryCast(grdBrokersPorvenir.Items(grdBrokersPorvenir.Items.Count - 1), CBrokerPorvenir)

                If brokerCambio.EsEditableNuevo Then
                    obcBrokersPorvenir.Remove(brokerCambio)
                    grdBrokersPorvenir.UpdateLayout()
                End If
        End Select
    End Sub
#End Region

#Region "TAB CLAVES OP"

    Private Sub CargaClavesOP()
        Dim dt As New DataTable()
        '123
        Dim eventoBit = CBitacoraFRIDA.GenerarEvento(CBitacoraFRIDA.CveEventosBit.CARGAR_CLAVES_OP, CServiciosMacrosSyBaseDB.IDUSUARIO, "CMConfigCOVAFTLPorvenir.xaml -> CMConfigCOVAFTLPorvenir_Loaded()")
        Try
            eventoBit.GuadarDetalle("tabla", "MMA_CAT_CLAVES_OP")
            Me.grdClavesOp.ItemsSource = COVAFTLServicio.ObtieneClavesOperacion()
            Me.grdClavesOp.UpdateLayout()
            eventoBit.ActualizarFechaFinDelEvento()
        Catch ex As Exception
            Dim errorBit = eventoBit.GuardarError("Error al cargar claves operacion: " & ex.Message)
            eventoBit.ActualizarFechaFinDelEvento()
            MessageBox.Show("Error TI500. Error al cargar claves operacion: " & ex.Message & " -Codigo:" & errorBit.IdError, "Configuración COVAFTL Porvenir", MessageBoxButton.OK, MessageBoxImage.Error)
        End Try
    End Sub

    Private Sub grdClavesOp_MouseRightButtonUp(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles grdClavesOp.MouseRightButtonUp
        Dim objDepend As DependencyObject = e.OriginalSource
        Dim celda As DataGridCell = Nothing
        Dim maxColumns = Me.grdClavesOp.Columns.Count
        Me.grdClavesOp.ContextMenu = Nothing
        While Not objDepend Is Nothing
            If objDepend.GetType().Name = "DataGridCell" Then
                celda = objDepend
                If celda.IsSelected = False Then
                    Me.grdClavesOp.UnselectAllCells()
                    celda.IsSelected = True
                End If

                celda.Focus()

                If celda.TabIndex <> maxColumns Then
                    Me.grdClavesOp.ContextMenu = AgregarMenuContextual(0)
                End If

                Exit While
            End If
            objDepend = VisualTreeHelper.GetParent(objDepend)
        End While
    End Sub

    Private Sub btnAgregarOp_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAgregarOp.Click
        Dim claveNueva As CClavesOp = New CClavesOp()
        Dim lstClaves As New ObservableCollection(Of CClavesOp)

        Me.grdClavesOp.UnselectAllCells()
        Me.grdClavesOp.UpdateLayout()

        lstClaves = Me.grdClavesOp.ItemsSource
        lstClaves.Add(claveNueva)

        Me.grdClavesOp.ScrollIntoView(Me.grdClavesOp.Items(Me.grdClavesOp.Items.Count - 1))
        Me.grdClavesOp.UpdateLayout()

        Dim celda As DataGridCell = ObtenerCelda(Me.grdClavesOp, Me.grdClavesOp.Items.Count - 1, 0)
        If Not celda Is Nothing Then
            celda.Focus()
            Me.grdClavesOp.BeginEdit()
            celda.IsSelected = True
        End If

        ValidaCantidadDatos(Me.grdClavesOp)
    End Sub

    Private Sub btnEliminaOp_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnEliminaOp.Click
        Dim claves As ObservableCollection(Of CClavesOp) = Me.grdClavesOp.ItemsSource
        Dim claveEliminar As New ObservableCollection(Of CClavesOp)
        Dim claveAgregado As New CClavesOp()
        Dim claveRecorrido As New CClavesOp()

        If Me.grdClavesOp.SelectedCells.Count > 0 Then
            For Each celda As DataGridCellInfo In Me.grdClavesOp.SelectedCells
                claveEliminar.Add(CType(celda.Item, CClavesOp))
            Next

            For Each T As CClavesOp In claveEliminar
                claves.Remove(T)
            Next

            Me.grdClavesOp.UpdateLayout()
        Else
            Dim msgBorrado As MessageBoxResult

            msgBorrado = MessageBox.Show("¿Desea borrar todos los registros no utilizados?", "Borrado claves", MessageBoxButton.YesNo, MessageBoxImage.Question)

            If (msgBorrado = MessageBoxResult.Yes) Then
                For Each ctAux As CClavesOp In claves
                    If ctAux.Mercado = "" And ctAux.TipoInversion = "" And ctAux.TipoTransaccion = "" And ctAux.TipoOperacion = "" And ctAux.InversionCovafsys = "" And ctAux.TransaccionCovafsys = "" And ctAux.DescripcionCovafsys = "" And ctAux.Comision = "0.00" And ctAux.Impuesto = "0.00" Then
                        claveEliminar.Add(ctAux)
                    End If
                Next

                For Each T As CClavesOp In claveEliminar
                    claves.Remove(T)
                Next

                Me.grdClavesOp.UpdateLayout()
                Me.grdClavesOp.Items.Refresh()
            End If
        End If

        ValidaCantidadDatos(Me.grdClavesOp)
    End Sub

    Private Sub grdClavesOp_BeginningEdit(ByVal sender As System.Object, ByVal e As System.Windows.Controls.DataGridBeginningEditEventArgs) Handles grdClavesOp.BeginningEdit
        claveEnEdicion = Me.grdClavesOp.CurrentItem
    End Sub

    Private Sub grdClavesOp_CellEditEnding(ByVal sender As System.Object, ByVal e As System.Windows.Controls.DataGridCellEditEndingEventArgs) Handles grdClavesOp.CellEditEnding
        Dim claveCambio As CClavesOp = New CClavesOp()
        Dim claveActual As CClavesOp
        Dim claves As ObservableCollection(Of CClavesOp) = Me.grdClavesOp.ItemsSource

        Select Case e.EditAction
            Case DataGridEditAction.Cancel
                claveCambio = TryCast(Me.grdClavesOp.Items(Me.grdClavesOp.Items.Count - 1), CClavesOp)

                If claveCambio.EsEditableNuevo Then
                    claves.Remove(claveCambio)
                    Me.grdClavesOp.UpdateLayout()
                End If
            Case DataGridEditAction.Commit
                If Not sender.CurrentItem Is Nothing Then
                    Dim txtContenidoCelda As Object = sender.Columns(e.Column.DisplayIndex).GetCellContent(sender.CurrentItem)
                    Dim Columna As Integer = e.Column.DisplayIndex
                    claveActual = TryCast(Me.grdClavesOp.CurrentCell.Item, CClavesOp)

                    Try
                        If Columna = 7 Or Columna = 8 Then
                            DirectCast(txtContenidoCelda, System.Windows.Controls.TextBox).Text = Convert.ToDouble(DirectCast(txtContenidoCelda, System.Windows.Controls.TextBox).Text).ToString("###,##0.00")
                        End If
                    Catch ex As Exception
                    End Try
                    claveActual.EsEditableNuevo = False
                End If
        End Select

        claveEnEdicion = Nothing
    End Sub

    Private Sub grdClavesOp_PreviewKeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Input.KeyEventArgs) Handles grdClavesOp.PreviewKeyDown
        If Keyboard.Modifiers = ModifierKeys.Control AndAlso e.Key = Key.C Then
            Try
                If copiarCeldas(Me.grdClavesOp) = False Then
                    MessageBox.Show("El rango de celdas seleccionado no es correcto, si está editando la celda favor de cancelar la edición y proceder con el copiado.", "Copiar celdas", MessageBoxButton.OK, MessageBoxImage.Exclamation)
                End If
            Catch ex As Exception
                MessageBox.Show("Error TI500. Al intentar copiar celdas: " & ex.Message, "Copiado", MessageBoxButton.OK, MessageBoxImage.Error)
            End Try
        End If
        If Keyboard.Modifiers = ModifierKeys.Control AndAlso e.Key = Key.V Then
            Try
                Dim col As Integer = Me.grdClavesOp.CurrentCell.Column.DisplayIndex
                Dim row As Integer = Me.grdClavesOp.Items.IndexOf(CType(Me.grdClavesOp.CurrentCell.Item, CClavesOp))
                Dim celda As DataGridCell = ObtenerCelda(Me.grdClavesOp, row, col)

                Me.grdClavesOp.CancelEdit()
                pegarDatos(Me.grdClavesOp)

            Catch ex As Exception
                MessageBox.Show("Error TI500. " & ex.Message, "Pegar celdas", MessageBoxButton.OK, MessageBoxImage.Error)

                Me.grdClavesOp.CancelEdit(DataGridEditingUnit.Cell)
            End Try
        End If
        If e.Key = Key.Delete Then
            Try
                Dim col As Integer = Me.grdClavesOp.CurrentCell.Column.DisplayIndex
                Dim row As Integer = Me.grdClavesOp.Items.IndexOf(CType(Me.grdClavesOp.CurrentCell.Item, CClavesOp))
                Dim celda As DataGridCell = ObtenerCelda(Me.grdClavesOp, row, col)

                If celda.IsEditing = False Then
                    BorraDatosSeleccionados(Me.grdClavesOp)
                End If
            Catch ex As Exception
                MessageBox.Show("Error TI500. " & ex.Message, "Borrar contenido de celdas", MessageBoxButton.OK, MessageBoxImage.Error)
            End Try
        End If
    End Sub

    Private Function AgregarMenuContextual(ByVal opcion As Integer) As ContextMenu
        Dim miMenuContextual As New ContextMenu
        Dim mnuCopia As New System.Windows.Controls.MenuItem
        Dim mnuPegar As New System.Windows.Controls.MenuItem
        Dim mnuInsertar As New System.Windows.Controls.MenuItem

        mnuCopia.Header = "Copiar"
        miMenuContextual.Items.Add(mnuCopia)
        AddHandler mnuCopia.Click, AddressOf mnuCopiar_click

        mnuInsertar.Header = "Insertar registros al final"
        miMenuContextual.Items.Add(mnuInsertar)
        AddHandler mnuInsertar.Click, AddressOf mnuInsertar_click

        'Este case esta preparado para extender la funcionalidad de las opciones del menú contextual
        Select Case opcion
            Case 0
                mnuPegar.Header = "Pegar"
                miMenuContextual.Items.Add(mnuPegar)
                AddHandler mnuPegar.Click, AddressOf mnuPegar_click
        End Select

        Return miMenuContextual
    End Function

    Private Sub mnuCopiar_click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Try
            Dim menuItem = CType(sender, MenuItem)
            Dim contextMenu = CType(menuItem.Parent, ContextMenu)
            Dim gridDeDatos = CType(contextMenu.PlacementTarget, DataGrid)
            If copiarCeldas(gridDeDatos) = False Then
                MessageBox.Show("El rango de celdas seleccionado no es correcto, si está editando la celda favor de cancelar la edición y proceder con el copiado.", "Copiar celdas", MessageBoxButton.OK, MessageBoxImage.Exclamation)
            End If
        Catch ex As Exception
            MessageBox.Show("Error TI500. Al intentar copiar celdas: " & ex.Message, "Copiado celdas", MessageBoxButton.OK, MessageBoxImage.Error)
        End Try
    End Sub

    Private Sub mnuPegar_click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Try
            Dim menuItem = CType(sender, MenuItem)
            Dim contextMenu = CType(menuItem.Parent, ContextMenu)
            Dim gridDeDatos = CType(contextMenu.PlacementTarget, DataGrid)
            pegarDatos(gridDeDatos)
        Catch ex As Exception
            MessageBox.Show("Error TI500. " & ex.Message, "Pegar celdas", MessageBoxButton.OK, MessageBoxImage.Exclamation)
        End Try
    End Sub

    Private Sub mnuInsertar_click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Try
            Dim menuItem = CType(sender, MenuItem)
            Dim contextMenu = CType(menuItem.Parent, ContextMenu)
            Dim gridDeDatos = CType(contextMenu.PlacementTarget, DataGrid)
            InsertarDatos(gridDeDatos)
        Catch ex As Exception
            MessageBox.Show("Error TI500. " & ex.Message, "Insertar registros", MessageBoxButton.OK, MessageBoxImage.Exclamation)
        End Try
    End Sub

    Private Function copiarCeldas(ByRef gridDeDatos As DataGrid) As Boolean
        Try
            Dim lstInterAux As ObservableCollection(Of CClavesOp) = gridDeDatos.ItemsSource
            Dim datos As New StringBuilder
            Dim copiadoCorrecto As Boolean = True
            Dim colIni As Integer = Integer.MaxValue
            Dim rowIni As Integer = Integer.MaxValue
            Dim colFin As Integer = Integer.MinValue
            Dim rowFin As Integer = Integer.MinValue
            Dim i As Integer = 0
            Dim j As Integer = 0

            Dim columnasIndex(gridDeDatos.SelectedCells.Count - 1) As Integer
            Dim renglonesIndex(gridDeDatos.SelectedCells.Count - 1) As Integer

            For Each celda As DataGridCellInfo In gridDeDatos.SelectedCells
                renglonesIndex(i) = gridDeDatos.Items.IndexOf(CType(celda.Item, CClavesOp))
                columnasIndex(j) = celda.Column.DisplayIndex
                i += 1
                j += 1
            Next

            rowIni = renglonesIndex.Min()
            rowFin = renglonesIndex.Max()
            colIni = columnasIndex.Min()
            colFin = columnasIndex.Max()

            For i = rowIni To rowFin
                For j = colIni To colFin
                    If EsSeleccionadaLaCelda(gridDeDatos, i, j) Then
                        'Dim colname As Integer = CClavesOp.IndexColumna(gridDeDatos.Columns(j).Header.ToString.Replace("_", ""))
                        'xxx
                        datos.Append(lstInterAux(i)(j).ToString() & vbTab)
                    Else
                        copiadoCorrecto = False
                        GoTo fuera
                    End If
                Next
                datos.Remove(datos.Length - 1, 1)
                datos.Append(vbLf)
            Next

            datos.Remove(datos.Length - 1, 1)

fuera:
            If copiadoCorrecto = True Then
                Clipboard.Clear()
                Clipboard.SetText(datos.ToString())
                Return True
            Else
                Return False
            End If
        Catch ex As Exception
            Throw ex
        End Try
    End Function

    Private Function EsSeleccionadaLaCelda(ByRef gridDeDatos As DataGrid, ByVal indexRow As Integer, ByVal indexCol As Integer) As Boolean
        Try
            Dim row As DataGridRow = gridDeDatos.ItemContainerGenerator.ContainerFromIndex(indexRow)
            Dim cellContent As TextBlock = gridDeDatos.Columns(indexCol).GetCellContent(row)
            Dim objDepend As DependencyObject = cellContent
            Dim celda As DataGridCell = Nothing

            While Not objDepend Is Nothing
                If objDepend.GetType().Name = "DataGridCell" Then
                    celda = objDepend

                    If celda.IsSelected = True Then
                        Return True
                    Else
                        Return False
                    End If
                End If
                objDepend = VisualTreeHelper.GetParent(objDepend)
            End While

            Return False
        Catch ex As Exception
            Return False
        End Try
    End Function

    Private Sub pegarDatos(ByRef gridDeDatos As DataGrid)
        Dim maxColumns = gridDeDatos.Columns.Count
        Dim lstInterAux As ObservableCollection(Of CClavesOp) = gridDeDatos.ItemsSource
        Dim datos As CDatosEnFormatoX
        datos = CUtileria.ObtenerDatosClipboard(vbLf, vbTab)

        '1) Validaciones: obtener información del portapapeles
        If datos.Datos.length = 0 Then
            Exit Sub
        End If

        If datos Is Nothing Then
            MessageBox.Show("No se pudo copiar los datos", "Pegado datos", MessageBoxButton.OK, MessageBoxImage.Error)
            gridDeDatos.CancelEdit(DataGridEditingUnit.Cell)
            Exit Sub
        End If

        '2) Validaciones: compatibilidad  
        Dim colTot As Integer = gridDeDatos.Columns.Count - 1
        Dim rowTot As Integer = gridDeDatos.Items.Count

        Dim colActual As Integer = gridDeDatos.SelectedCells.First.Column.DisplayIndex
        Dim rowActual As Integer = gridDeDatos.Items.IndexOf(CType(gridDeDatos.SelectedCells.First.Item, CClavesOp))

        If colActual <> maxColumns Then

            'Validar renglones
            If datos.NumeroRenglones > ((rowTot - (rowActual + 1)) + 1) Then
                MessageBox.Show("No coinciden las dimensiones de datos a pegar (R)", "Pegado datos", MessageBoxButton.OK, MessageBoxImage.Error)
                gridDeDatos.CancelEdit(DataGridEditingUnit.Cell)
                Exit Sub
            End If

            If datos.NumeroColumnas.Max > ((colTot - (colActual + 1)) + 1) Then
                MessageBox.Show("No coinciden las dimensiones de datos a pegar (C), recuerde que la columna Mensaje solo es informativa", "Pegado datos", MessageBoxButton.OK, MessageBoxImage.Error)
                gridDeDatos.CancelEdit(DataGridEditingUnit.Cell)
                Exit Sub
            End If

            '2) Realizar copiado  
            Dim i As Integer = 0
            Dim j As Integer = 0

            Dim coontador As Integer = 0
            Dim limRow As Integer = (rowActual + (datos.NumeroRenglones - 1))

            gridDeDatos.UnselectAllCells()

            Try
                For i = rowActual To limRow
                    Dim limCol As Integer = (colActual + (datos.NumeroColumnas(coontador) - 1))

                    For j = colActual To limCol
                        If datos.Datos(i - rowActual)(j - colActual) <> vbLf Then 'And (Not CType(datos.Datos(i - rowActual)(j - colActual), String).Trim().Equals("")) Then
                            Dim row As DataGridRow = gridDeDatos.ItemContainerGenerator.ContainerFromIndex(i)
                            Dim cellContent As TextBlock = gridDeDatos.Columns(j).GetCellContent(row)

                            Dim auxImpDos As String = datos.Datos(i - rowActual)(j - colActual).ToString.Trim()

                            Try
                                If j = 7 Or j = 8 Then
                                    auxImpDos = Convert.ToDouble(auxImpDos).ToString("###,##0.00")
                                End If


                                cellContent.Text = auxImpDos
                                'xxx
                                'Dim colname As Integer = CClavesOp.IndexColumna(gridDeDatos.Columns(j).Header.ToString.Replace("_", ""))
                                lstInterAux(i)(j) = auxImpDos
                            Catch ex As Exception
                                cellContent.Text = auxImpDos
                                'xxx
                                'Dim colname As Integer = CClavesOp.IndexColumna(gridDeDatos.Columns(j).Header.ToString.Replace("_", ""))
                                lstInterAux(i)(j) = auxImpDos
                            End Try

                            seleccionarcelda(gridDeDatos, i, j)
                        End If
                    Next
                    coontador += 1
                Next
            Catch ex As Exception
                gridDeDatos.Items.Refresh()

                Throw New Exception("No se pudo terminar de copiar los datos debido a que no coinciden con el formato especificado para cada celda", ex)
            End Try
        End If
    End Sub

    Private Sub seleccionarcelda(ByRef gridDeDatos As DataGrid, ByVal indexRow As Integer, ByVal indexCol As Integer)
        Dim row As DataGridRow = gridDeDatos.ItemContainerGenerator.ContainerFromIndex(indexRow)
        Dim cellContent As TextBlock = gridDeDatos.Columns(indexCol).GetCellContent(row)
        Dim objDepend As DependencyObject = cellContent
        Dim celda As DataGridCell = Nothing

        While Not objDepend Is Nothing
            If objDepend.GetType().Name = "DataGridCell" Then
                celda = objDepend

                If celda.IsSelected = False Then
                    celda.IsSelected = True
                    celda.Focus()
                    Exit While
                End If
            End If
            objDepend = VisualTreeHelper.GetParent(objDepend)
        End While
    End Sub

    Private Sub InsertarDatos(ByRef gridDeDatos As DataGrid)
        Dim lstInterAux As ObservableCollection(Of CClavesOp) = gridDeDatos.ItemsSource
        Dim datos As CDatosEnFormatoX

        datos = CUtileria.ObtenerDatosClipboard(vbLf, vbTab)

        '1) Validaciones: obtener información del portapapeles
        If datos.Datos.length = 0 Then
            Exit Sub
        End If

        If datos Is Nothing Then
            MessageBox.Show("No se pudo copiar los datos", "Insertado registros", MessageBoxButton.OK, MessageBoxImage.Error)
            gridDeDatos.CancelEdit(DataGridEditingUnit.Cell)
            Exit Sub
        End If

        '2) Validaciones: compatibilidad  
        Dim colTot As Integer = gridDeDatos.Columns.Count - 1

        'Validar solo columnas
        If datos.NumeroColumnas.Max <> colTot Then
            MessageBox.Show("El número de columnas es incorrecto, favor de revisar la información copiada", "Insertado registros", MessageBoxButton.OK, MessageBoxImage.Error)
            gridDeDatos.CancelEdit(DataGridEditingUnit.Cell)
            Exit Sub
        Else
            Dim lstClaves As New ObservableCollection(Of CClavesOp)

            lstClaves = gridDeDatos.ItemsSource

            For renglon = 0 To datos.NumeroRenglones - 1 Step 1

                Dim claveI As New CClavesOp()

                claveI.Mercado = datos.Datos(renglon)(0).ToString().Trim()
                claveI.TipoInversion = datos.Datos(renglon)(1).ToString().Trim()
                claveI.TipoTransaccion = datos.Datos(renglon)(2).ToString().Trim()
                claveI.TipoOperacion = datos.Datos(renglon)(3).ToString().Trim()
                claveI.InversionCovafsys = datos.Datos(renglon)(4).ToString().Trim()
                claveI.TransaccionCovafsys = datos.Datos(renglon)(5).ToString().Trim()
                claveI.DescripcionCovafsys = datos.Datos(renglon)(6).ToString().Trim()
                Try
                    claveI.Comision = Convert.ToDouble(datos.Datos(renglon)(7).ToString().Trim()).ToString("###,##0.00")
                Catch ex As Exception
                    claveI.Comision = datos.Datos(renglon)(7).ToString().Trim()
                End Try
                Try
                    claveI.Impuesto = Convert.ToDouble(datos.Datos(renglon)(8).ToString().Trim()).ToString("###,##0.00")
                Catch ex As Exception
                    claveI.Impuesto = datos.Datos(renglon)(8).ToString().Trim()
                End Try
                claveI.Calcular = datos.Datos(renglon)(9).ToString().Trim()

                lstClaves.Add(claveI)
            Next

            gridDeDatos.UpdateLayout()

            ValidaCantidadDatos(gridDeDatos)
        End If
    End Sub

    Private Sub ValidaCantidadDatos(ByRef gridDeDatos As DataGrid)

        If gridDeDatos.Items.Count > 0 Then
            btnEliminaOp.IsEnabled = True
        Else
            btnEliminaOp.IsEnabled = False
        End If

    End Sub

    Private Sub BorraDatosSeleccionados(ByRef gridDeDatos As DataGrid)

        Dim lstInterAux As ObservableCollection(Of CClavesOp)

        lstInterAux = gridDeDatos.ItemsSource
        Try
            For Each celda As DataGridCellInfo In gridDeDatos.SelectedCells
                Dim col As Integer = celda.Column.DisplayIndex
                Dim row As Integer = gridDeDatos.Items.IndexOf(CType(celda.Item, CClavesOp))

                Dim rowData As DataGridRow = gridDeDatos.ItemContainerGenerator.ContainerFromIndex(row)
                Dim cellContent As TextBlock = gridDeDatos.Columns(col).GetCellContent(rowData)
                cellContent.Text = CClavesOp.ValorInicalColumna(col)
                'xxx
                'Dim colname As Integer = CClavesOp.IndexColumna(gridDeDatos.Columns(col).Header.ToString.Replace("_", ""))
                lstInterAux(row)(col) = CClavesOp.ValorInicalColumna(col)
            Next

        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub btnGuardarOp_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnGuardarOp.Click
        Mouse.OverrideCursor = Cursors.Wait
        '123
        Dim eventoBit = CBitacoraFRIDA.GenerarEvento(CBitacoraFRIDA.CveEventosBit.GUARDAR_CLAVES_OP, CServiciosMacrosSyBaseDB.IDUSUARIO, "CMConfigCOVAFTLPorvenir.xaml -> btnGuardarOp")
        Try
            Dim lst = Me.grdClavesOp.ItemsSource
            Dim strError As String = ""
            
            If COVAFTLServicio.ActualizaClavesOp(lst, strError) Then
                eventoBit.GuadarDetalle("lista", lst.ToString)
                eventoBit.ActualizarFechaFinDelEvento()
                CargaClavesOP()
                MessageBox.Show("Operación Exitosa", "Configuración COVAFTL Porvenir", MessageBoxButton.OK, MessageBoxImage.Information)
            Else
                Dim errorBit = eventoBit.GuardarError("Error al claves de operación: " & strError)
                eventoBit.ActualizarFechaFinDelEvento()
                MessageBox.Show("Error TI500. Error al guardar información: " & strError & " -Codigo:" & errorBit.IdError, "Configuración COVAFTL Porvenir", MessageBoxButton.OK, MessageBoxImage.Error)
            End If


        Catch ex As Exception
            Dim errorBit = eventoBit.GuardarError("Error al claves de operación: " & ex.Message)
            eventoBit.ActualizarFechaFinDelEvento()
            MessageBox.Show("Error TI500. Error al guardar información: " & ex.Message & " -Codigo:" & errorBit.IdError, "Configuración COVAFTL Porvenir", MessageBoxButton.OK, MessageBoxImage.Error)
            Mouse.OverrideCursor = Nothing
        End Try
        Mouse.OverrideCursor = Nothing
    End Sub
#End Region
End Class
